# -*- codeing = utf-8 -*-

from django.utils.safestring import mark_safe


class SelectFilter(object):
    """此类有__iter__方法，是一个可迭代对象"""

    def __init__(self, name, data_list, request):
        self.name = name
        self.data_list = data_list
        print(data_list)
        self.request = request

    def __iter__(self):
        yield mark_safe("<select class='select2' multiple='multiple' style='width:100%;' >")
        for item in self.data_list:
            key = str(item[0])
            text = item[1]

            selected = ""
            value_list = self.request.GET.getlist(self.name)
            if key in value_list:
                selected = 'selected'
                value_list.remove(key)
                print(value_list, 1)  # debug
            else:
                value_list.append(key)
                print(value_list, 2)  # debug

            query_dict = self.request.GET.copy()
            # print(query_dict)
            # <QueryDict: {'page': ['1'], 'status': ['1', '2'],'priority': 'danger',}>
            query_dict._mutable = True  # 设置query_dict允许修改
            query_dict.setlist(self.name, value_list)  # {"status":[1,2]&"priority":"danger"}
            if 'page' in query_dict:
                """结合分页器v2使用时，去掉ur中的page分页参数"""
                query_dict.pop('page')

            param_url = query_dict.urlencode()
            """无参数时去url结尾?处理"""
            if param_url:
                url = "{}?{}".format(self.request.path_info, param_url)  # status=1&status=2&priority=danger
            else:
                url = self.request.path_info

            html = "<option value={url} {selected} >{text}</option>".format(url=url, selected=selected, text=text)
            yield mark_safe(html)
        yield mark_safe("</select>")
